package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.mapper.OrderDetailMapper;
import com.itheima.mapper.OrdersMapper;
import com.itheima.service.OrdersService;
import com.itheima.vo.OrdersVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单service
 */
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;
    /**
     * 分页查询订单
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Page<OrdersVo> page(Integer page, Integer pageSize, Long number, LocalDateTime beginTime, LocalDateTime endTime) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(number != null, Orders::getId, number);
        queryWrapper.gt(beginTime != null, Orders::getOrderTime, beginTime);
        queryWrapper.lt(endTime != null, Orders::getOrderTime, endTime);
        ordersMapper.selectPage(ordersPage, queryWrapper);

        //封装ordersVo
        Page<OrdersVo> ordersVoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, ordersVoPage, "records");
        List<Orders> ordersList = ordersPage.getRecords();
        if (ordersList != null) {
            List<OrdersVo> list = ordersList.stream().map((item) -> {
                OrdersVo ordersVo = new OrdersVo();
                BeanUtils.copyProperties(item, ordersVo);
                Long id = item.getId();
                if (id != null) {
                    LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(OrderDetail::getOrderId,id);
                    List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);
                    ordersVo.setOrderDetailList(orderDetails);
                }
                return ordersVo;
            }).collect(Collectors.toList());
            ordersVoPage.setRecords(list);
        }
        return ordersVoPage;
    }
}
